﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text; 
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace MyWeb.Areas.Community.Controllers
{
    [Area("Community")] 
    public class DiscussController : Controller
    { 
        private readonly IHostingEnvironment _host;

        public DiscussController(IHostingEnvironment host)
        {
            _host = host;
        }

        public IActionResult Page(int id = 0)
        { 
            return View();
        }
         
        public IActionResult Detail(int id)
        {
            ViewBag.Id = id;
            return View();
        }

        public IActionResult Add()
        {
            return View();
        }

        [HttpGet]
        public JsonResult GetJson(int index, int size)
        {
            List<object> list = new List<object>();
            for (int i = 1; i < 100; i++)
            {
                object temp = new { id = i, name = "wbs" + i, title = "文章" + i };
                list.Add(temp);
            }

            List<object> data = list.Skip((index - 1) * size).Take(size).ToList();

            JsonResult json = new JsonResult(new { count = list.Count, list = data });
            return Json(json);
        }


        [HttpPost]
        public object UploadFile()
        {
            IFormFileCollection files = Request.Form.Files;
            if (files == null || files.Count < 1)
                return "上传失败，文件为空！";

            List<string> listname = new List<string>();

            foreach (IFormFile file in files)
            {
                Stream stream = file.OpenReadStream();

                int len = Convert.ToInt32(stream.Length);
                byte[] b = new byte[len];
                stream.Read(b, 0, len);

                WebClient w = new WebClient();
                w.QueryString.Add("FileType", file.FileName);
                byte[] result = w.UploadData("http://localhost:5000/api/Files/uploadbyte", "POST", b);
                string str = Encoding.UTF8.GetString(result).Replace("\"", ""); ;
                listname.Add(str);
            }
            if (listname.Count < 0)
                return new { status = -1, url = "error" };
            return new { status = 0, url = listname };
        }
    }
}